<?php
namespace app\modules\epi\controllers;

use Yii;
use ac\controllers\AuthController;
use app\models\GoodsCategory;
use app\models\GoodsCategorySearch;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use ac\behaviors\Sort;


class GoodsCategoryController extends AuthController
{

    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

	/*栏目列表*/
    public function actionCategoryList()
    {
        // P($this->get);
        $search = (new GoodsCategorySearch())->search($this->get);
        if($search === false){//验证搜索参数不通过
            $count = 0;
            $goodsCategoryList = array();
        }else{
            if(isset($this->get['type']) and $this->get['type'] == 'ele'){
                $flag = 'ele';
            }else{
                $flag = '';
            }
            if(isset( $this->get['parentid'] )){
                $parentid = $this->get['parentid'];
            }else{
                $parentid = 0;
            }
            // P($search);
            $goodsCategoryList = GoodsCategory::getTreeList($search, $flag, $parentid);
        }
        return Tool::showRes([0, '获取成功'], $goodsCategoryList);
    }

    /*添加栏目*/
    public function actionAddCategory()
    {
        if(Yii::$app->request->isPost){
            $goodsCategory = new GoodsCategory;

            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*添加栏目*/
                if( ($catid = $goodsCategory->addCategory($this->post)) == false){
                    $pass = false;
                    if($goodsCategory->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $goodsCategory->getErrors();//异常信息
                    }else{
                        throw new \Exception('添加栏目异常失败');
                    }
                }

                if($pass){
                    $backInfo = [0, '添加栏目成功'];//返回信息
                    $transaction->commit();
                }


            }catch(\Exception $exception){
                $transaction->rollback();       
            };


        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改栏目
    */
    public function actionModifyCategory()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $catid = isset($this->get['catid'])?$this->get['catid']:'';
            if($catid){
                $goodsCategory = GoodsCategory::find()
                        ->where('catid = :catid', [':catid' => $catid])->asArray()->one();
                if(!is_null($goodsCategory)){
                    if(!empty($goodsCategory['icon'])){
                        $goodsCategory['icon'] = explode(',', $goodsCategory['icon']);
                    }
                    if(!empty($goodsCategory['preview'])){
                        $goodsCategory['preview'] = explode(',', $goodsCategory['preview']);
                    }
                    $data = array(
                        'category' => $goodsCategory
                    );

                    return Tool::showRes([0, '获取成功'], $data);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $catid = isset($this->post['GoodsCategory']['catid'])?intval($this->post['GoodsCategory']['catid']):'';
            if(!$catid){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*修改栏目信息*/
                    $goodsCategory = new GoodsCategory;
                    if(!$goodsCategory->modifyCategory($this->post, $catid)){
                        if($goodsCategory->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $goodsCategory->getErrors();//异常信息
                        }else{
                            throw new \Exception('修改栏目失败');
                        }
                        $pass = false;
                    }

                    if($pass){
                        $backInfo = [0, '修改栏目成功'];//返回信息
                        $transaction->commit();
                    }


                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*是否显示1-不显示-2显示（是否显示操作）*/
    public function actionSetDisplay()
    {
        if(Yii::$app->request->isPost){
            $catid = isset($this->post['catid'])?$this->post['catid']:'';
            $goodsCategory = GoodsCategory::find()->select('display')
                                ->where('catid = :catid', [':catid' => $catid])->one();
            // P($goodsCategory);
            if(!is_null($goodsCategory)){
                $goodsCategory->updateAll(['display' => Tool::changeBool($this->post['display']),], 'catid = :catid', [':catid' => $catid]);
                $backInfo = [0, '设置栏目显示状态成功'];//返回信息
            };
        }

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    排序
    tree型数据，是按照sort正序排列
    */
    public function actionSetSort()
    {
       if(Yii::$app->request->isPost){
            // P($this->post);
            //取出被排序的数据
            $sortId = isset($this->post['sort'])?$this->post['sort']:'';
            //目标对象  ‘before’在之上面，否则在下面
            $targetId = isset($this->post['target'])?$this->post['target']:'';
            if($sortId and $targetId){
                if($this->setSortTreeList(new GoodsCategory, $sortId, $targetId, $this->post['location'])){
                    $backInfo = [0, '设置栏目排序成功'];//返回信息
                }
            }
            // P($backInfo);

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };


       }
       return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除栏目,包括子栏目（真删除）*/
    public function actionDeleteCategory()
    {
        $catid = isset($this->get['catid'])?$this->get['catid']:'';
        if($catid){
            $goodsCategory = new GoodsCategory;
            if(($res = $goodsCategory->deleteCategory($catid)) === true){
                $backInfo = [0, '删除栏目成功'];//返回信息
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), '') ) != 'boolean'){
                    return $res;
                };
            }else{
                return Tool::showRes(ErrMap::getError($res));
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*检查父ID是否存在*/
    private function checkHasParId($catid)
    {
        if($catid == 0){
            return true;
        }
        $goodsCategory = GoodsCategory::find()->where('catid = :catid', [':catid' => $catid])->one();
        // P($goodsCategory);
        if(is_null($goodsCategory)){
            return false;
        }else{
            return true;
        };
    }



}